package fmanganiello.tests.javatests.guava;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;

import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;

public class Subscriber implements Runnable {
	private EventBus eventBus;
	private CountDownLatch latch;
	private long subscribeTimeout;
	private boolean subscribeTimedOut;
	private final AtomicReference<Boolean> eventReceived = new AtomicReference<>(false);
	
	public Subscriber(final EventBus eventBus, final CountDownLatch latch, long subscribeTimeout) {
		this.eventBus = eventBus;
		this.latch = latch;
		this.subscribeTimeout = subscribeTimeout;
		this.subscribeTimedOut = false;
	}

	public void run() {
		System.out.println(Subscriber.class + ": Subscriber started - Thread ID: " + Thread.currentThread().getId());
		eventBus.register(this);
		synchronized(eventReceived) {
			try {
				eventReceived.wait(subscribeTimeout);
			} catch (InterruptedException e) {}
		}
		
		if (eventReceived.get() == false) {
			subscribeTimedOut = true;
			latch.countDown();
		}
	}
	
	@Subscribe
	public void handlePurchaseEvent(PurchaseEvent event) {
		if (!subscribeTimedOut) {
			System.out.println(Subscriber.class + ": Received purchase event: " + event.getInstrument() + ", " + event.getAmount());
			latch.countDown();
			
			synchronized(eventReceived) {
				eventReceived.set(true);
			}
		}
	}
	
	public synchronized boolean wasEventReceived() {
		return eventReceived.get();
	}
}
